package ar.com.ford.it.fullEconomics.persistence.dao.query;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.GregorianCalendar;
import oracle.toplink.expressions.Expression;
import oracle.toplink.expressions.ExpressionBuilder;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese01Economic;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese03Econvalue;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import com.ford.it.persistence.impl.toplink.CustomExpressionFactory;

public class FindEconomicPeriodValuesQuery implements CustomExpressionFactory {

    public Expression createExpression(ExpressionBuilder builder,
            Object[] parameters) {
        Expression exp = null;
        Teese03Econvalue ecoV = (Teese03Econvalue) parameters[0];
        Timestamp fechaStart = ecoV.getEese03EcvalueEffectivDateY();
        Timestamp fechaEnd = ecoV.getEese03EcvalueEffectivDateY();
        Teese01Economic findEco = ecoV.getTeese01Economic();

        if (findEco.getEese01EconQuantityTypeC().equals("D")) {
            fechaEnd = fechaMasDias(fechaEnd, findEco
                    .getEese01EconQuantityQ());
        }
        if (findEco.getEese01EconQuantityTypeC().equals("M")) {
            fechaEnd = fechaMasMeses(fechaEnd, findEco
                    .getEese01EconQuantityQ());
        }

        String findState = ecoV.getEese03CreateUserC();

        Teesg01Plant plant = ecoV.getEese03PlantCodeC();
        exp = builder.get("eese03PlantCodeC").equal(plant);
        if (findEco != null) {
            exp = exp.and(builder.get("teese01Economic").equal(findEco));
        }
        if (findState != null) {
            if ("aprobados".equals(findState))
                exp = exp.and(builder.get("eese03EcvalueApprovalS").notNull());
            if ("registrados".equals(findState))
                exp = exp.and(builder.get("eese03LastUserUpdtC").notNull());
        }
        // Busqueda entre fechas en tre la fecha que ingreso mas la fecha que
        // ingreso mas la frequencia de actualizacion del indice economico
        exp = exp.and(builder.get("eese03EcvalueEffectivDateY").greaterThanEqual(fechaStart));
        exp = exp.and(builder.get("eese03EcvalueEffectivDateY").lessThanEqual(fechaEnd));
        return exp;
    }

    public Timestamp fechaMasDias(Timestamp fch, int dias) {
        Calendar cal = new GregorianCalendar();
        cal.setTimeInMillis(fch.getTime());
        cal.add(Calendar.DATE, dias);
        return new Timestamp(cal.getTimeInMillis());
    }

    public Timestamp fechaMasMeses(Timestamp fch, int dias) {
        Calendar cal = new GregorianCalendar();
        cal.setTimeInMillis(fch.getTime());
        cal.add(Calendar.MONTH, dias);
        return new Timestamp(cal.getTimeInMillis());
    }
}
